# -*- coding: utf-8 -*-
"""
@Time ： 2023/3/7 17:05
@Author ： ChuiZi
@File ：reportPatch.py
@IDE ：PyCharm
"""
import os
import re
import json

from lib.common.achievePath import Find
from options.configs import FrameDataPath
from settings import allureTap, allureTapStory, allureTapFeature, allureTapEpic


# 自定义测试报告样式
def htmlReportPatch(reportpath=None):
    """限定于pytest-reporthtml插件生成的测试报告的编码错误
    :param reportpath: 测试报告绝对路径,默认为测试报告文件夹内最新生成的测试报告
    """
    if reportpath is None:
        reportpath = Find.suffixeAbsPaths(FrameDataPath.pathReportRootDir, "html")[0]

    testdata = {}
    with open(FrameDataPath.pathTestCaseTempData, "r", encoding="utf-8") as f1:
        allcase = json.load(f1)
        for story in allcase:
            testdata.update(story[1])
    with open(reportpath, "r", encoding='utf-8') as f1, open(newReportPath := reportpath + ".temp", "w",
                                                             encoding='utf-8') as f2:
        file1 = f1.read()
        pattern_all_case = re.compile('<tr class="case_">.*<[/]tr>', re.S)  # 通过贪婪匹配到所有用例数据
        all_case = re.search(pattern_all_case, file1)
        all_case_info = {"start_point": all_case.start(), "end_point": all_case.end(),
                         "data": all_case.group()}  # 测试用例所有数据在整个file文件的数据,和范围
        # 单独处理日志和用例数据
        pattern_each_case = re.compile('<tr class="case_">.*?<[/]tr>', re.S)
        pattern_each_caselog = re.compile('<tr class="test_log">.*?<[/]tr>', re.S)
        each_case = re.findall(pattern_each_case, all_case_info["data"])
        each_caselog = re.findall(pattern_each_caselog, all_case_info["data"])

        pattern_each_case_info = re.compile(r'.*?\n', re.S)
        pattern_each_case_text = re.compile(r'>.*?<')

        all_case_changed = ""
        # 修改每一个用例展示数据
        for i in range(len(each_case)):
            case_infos = re.findall(pattern_each_case_info, each_case[i])
            # 开始修改用例数据,序号2:用例模块所属,序号3:方法名称,序号4:用例描述
            case_infos[2] = case_infos[2]
            case_infos[4] = case_infos[4].encode("utf-8").decode("unicode_escape")  # 修复编码错误
            # 获取定位
            text = re.search(pattern_each_case_text, case_infos[4]).group()[1:-1]
            case_data = testdata.get(text).get(allureTap)
            case_infos[3] = re.sub(pattern_each_case_text,
                                   f">{case_data[allureTapFeature]}-{case_data[allureTapStory]}<", case_infos[3])
            # 重新组合成case
            case = ""
            for cas_info in case_infos:
                case = case + cas_info
            all_case_changed = all_case_changed + case + each_caselog[i]
        # 将修复后的用例展示数据重新写入文件中
        file2 = all_case_changed
        f2.write(file1[:all_case_info["start_point"]] + file2 + file1[all_case_info["end_point"]:])
    os.remove(reportpath)
    os.rename(newReportPath, reportpath)


if __name__ == '__main__':
    report = Find.suffixeAbsPaths(FrameDataPath.pathReportRootDir, "html")[0]
    # print(report)
    htmlReportPatch(report)
